﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Dukou
{
    public class Ext
    {
        public static MvcHtmlString create(string className, object config)
        {
            return MvcHtmlString.Create(string.Format("Ext.create('{0}', {1});", className, ToObject(config)));
        }

        public static string ToObject(object obj)
        {
            StringBuilder strBuilder = new StringBuilder();
            if (obj != null)
            {
                foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
                {
                    strBuilder.Append(string.Format("{0}: {1},", descriptor.Name, descriptor.GetValue(obj)));
                }
            }


            return string.Format("{{{0}}}", strBuilder.ToString().TrimEnd(','));
        }

        public static string ToArray(IList<object> array)
        {
            if (array == null)
            {
                return "null";
            }
            StringBuilder strBuilder = new StringBuilder();
            foreach (var item in array)
            {
                strBuilder.Append(",");
                strBuilder.AppendLine(ToObject(item));
            }
            return string.Format("[{0}]", strBuilder.ToString().TrimStart(','));
        }
    }

    public class Javascript : IDisposable
    {
        private HtmlHelper _htmlHelper;

        public Javascript(HtmlHelper htmlHelper)
        {
            _htmlHelper = htmlHelper;
            _htmlHelper.ViewContext.Writer.Write(@"<script type=""text/javascript"">");
        }

        public Javascript(HtmlHelper htmlHelper, string src)
        {
            _htmlHelper = htmlHelper;
            _htmlHelper.ViewContext.Writer.Write(string.Format(@"<script type=""text/javascript"" src=""{0}"">", src));
        }

        public void Dispose()
        {
            _htmlHelper.ViewContext.Writer.Write("</script>");
        }

        public JsIF IF()
        {
            return new JsIF(_htmlHelper);
        }

        public void Assign()
        {
 
        }

    }

    public class JsIF : IDisposable
    {
        private HtmlHelper _htmlHelper;
 
        internal JsIF(HtmlHelper htmlHelper)
        {
            _htmlHelper = htmlHelper;
            _htmlHelper.ViewContext.Writer.Write("if () {");
            _htmlHelper.ViewContext.Writer.Write(Environment.NewLine);
        }

        public void Dispose()
        {
            _htmlHelper.ViewContext.Writer.Write("}");
        }
    }

    public class Function
    {
        private string name;

        public Function(string name)
        {
            this.name = name;
        }

        public string Excute()
        {
            return string.Format("{0}();", this.name);
        }
    }
}
